/*-----------------------------------------------------------------------------
* @Description:     问卷管理添加
* @Version:         1.0.0
* @author:          yudan(862669640@qq.com)
* @date             2017.11.29
* ==NOTES:=============================================
* v1.0.0(2017.11.29):
     初始生成
* ---------------------------------------------------------------------------*/
$(function(){
/*********************************************函数调用********************************************************************/
	
/*********************************************事件绑定********************************************************************/
	/*
		J_del的css：页面进来，删除按钮就是灰色的（因为只有一个问题）
	*/
	$('.J_del').css('color','grey');
	/*
		添加考核项
	*/
	$(document).on('click','.J_addOption',function(e){
		addOption(e);
	});
	/*
		添加考核对象
	*/
	$(document).on('click','.J_addTeacher',function(){
		addTeacher();
	});
	/*
		删除考核项
	*/
	$(document).on('click','.J_delOption:eq(-1)',function(){
		delOption();
	});
	/*
		删除考核对象
	*/
	$(document).on('click','.J_delTeacher:eq(-1)',function(){
		delTeacher();
	});
	/*
		添加问题
	*/
	$('.J_addQuestion').click(function(){
		formValidatorAddQuestionForm();
		var 
			form = $('.J_optionForm:eq(-1)'),
            data = form.data('bootstrapValidator');
        if (data) {
            data.validate();

            if (!data.isValid()) {
                return false;
            }else{
            	addQuestion(); 
                return true;
            }
        }
	});
	/*
		保存问卷
		(得验证外面的form对不对&&问题的最后一个form对不对，都对了才能发数据)
	*/
	$(document).on('click','.J_save',function(e){
		var optionForm = $('.J_optionForm'),//问题form
            teacherForm = $('.J_teacherForm'),//老师form
			length = optionForm.length,//问题的个数
			optionLength,//每个问题的option个数
			optionData = [],
            teacherData = [],
			optionResult,//每一个问题的验证结果
            teacherResult,//每一个techerForm的验证结果
			i,
			data1=true;//用来存放总的验证结果
		
		for(i=0;i<length;i++){

			optionLength = optionForm.eq(i).find(".panel-option").length;

			if(optionForm.eq(i).data('bootstrapValidator')){
				optionForm.eq(i).data('bootstrapValidator').destroy();
			}

			formValidatorAllQuestionForm(i,optionLength);//验证optionForm问题框对不对
			optionResult = optionForm.eq(i).data('bootstrapValidator');//验证问题内容对不对
            formValidatorAllTeacherQuestionForm(i,optionLength);//验证teacherForm问题框对不对
            teacherResult = teacherForm.eq(i).data('bootstrapValidator');//验证问题内容对不对
            

			if(optionResult){
				optionResult.validate();//循环地把每个问题的验证结果放到数组里
				optionData[i] = optionResult.isValid(); 
			}
            if(teacherResult){
                teacherResult.validate();//循环地把每个问题的验证结果放到数组里
                teacherData[i] = teacherResult.isValid(); 
            }
			if(length < 2){
				data1 = optionData[0];//进行第一次循环，或者只有一个问题
                data4 = teacherData[0];//进行第一次循环，或者只有一个问题
			}else{
				data1 = data1 && optionData[i];
                data4 = data4 && teacherData[i];
			}
		}
		
		formValidatorAddForm();//验证外边的信息对不对
		
		var
			form = $(".J_formKaohe"),//外边的form
            data2 = form.data('bootstrapValidator'),//验证外面的input对不对
            data3 = validEndTime();//验证问卷截止时间对不对

        if (data2) {
            data2.validate();

        	if(!data1){
				return false;
        	}else if(!data4){
                return false;
            }else if(data2.isValid() && data3){
        		save(e);
                return true;
        	}else{
        		return false;
        	}
        	
        }
	});
	/**
     * 点击form区域，验证截止时间
     */
 	$('.J_endTime').blur(function(){
        validEndTime();
    });
	/*
		选择多选按钮，提示多选的要求
	*/
	$(document).on('click','.optionsRadios',function(e){
		showRequirement(e);
	});
	/*
		点击收起，收起当前问题框
	*/
	$(document).on('click','.J_retract',function(e){
		retractQuestion(e);
	})
	/*
		点击编辑，展开当前问题框
	*/
	$(document).on('click','.J_edit',function(e){
		editQuestion(e);
	})
	/*
		点击删除，删除当前问题框
	*/
	$(document).on('click','.J_del',function(e){
		delQuestion(e);
	})
	/**
     * 角色点击更改
     */
	$(document).on('change', '.J_selectRole', function(e){
		selectRoleChange(e);
	});
/*********************************************函数声明********************************************************************/
	
	/*
		添加考核项
	*/
	function addOption(e){
		var optionLength = $('.J_optionForm .optionName').length,
            limitLen = optionLength + 1,
			dom = '<div class="form-group panel-option J_optionList">\
			        	<label class="col-sm-2 control-label optionName"></label>\
				        <div class="col-sm-7">\
				            <input class="new220 J_option" limitIndex = "'+ optionLength +'" type="text" name="option" value="先进"/>\
				            <a href="javascript:;" class="J_delOption margin-left2">删除考核项</a>\
				        </div>\
				    </div>\
				    <div class="form-group optionType">\
                        <label class="col-sm-2 control-label" for="name"><span class="requires">*</span>答题形式</label>\
                        <div class="J_type">\
                            <label class="radio-inline">\
                                <input type="radio" name="optionsRadiosinline '+ optionLength +'" class="optionsRadios" value="1" checked /> 单选\
                            </label>\
                            <label class="radio-inline">\
                                <input type="radio" name="optionsRadiosinline '+ optionLength +'" class="optionsRadios"  value="2" /> 多选\
                            </label>\
                        </div>\
                    </div>',
            limitIndex = '<div class="form-group J_checkOption">\
                            <label class="col-sm-2-2 control-label "><span class="requires">*</span>考核项'+ limitLen +' 数量上限</label>\
                            <div class="J_limit col-sm-4-7">\
                                <input class="new40 J_limitNum"  limitIndex = "'+ optionLength +'" placeholder="考核项多选个数"  type="text" name="remindaheadDays" disabled = "disabled" value="1"/>\
                            </div>\
                        </div>';
		$('.optionType:eq(-1)').after(dom);
		$('.optionName').last().html('<span class="requires">*</span>考核项'+limitLen);
		$('.J_delOption:eq(-2)').css('display','none');
        $('.J_checkList').append(limitIndex);

	}
	/*
		添加考核对象
	*/
    var groupDom = $('.panel-teacher').html();//获取考核组别的html
	function addTeacher(){
		var optionLength = $('.teacherName').length + 1,
            limitDom = $('.J_checkList:eq(0)').html(),
            dom = '<div  class="form-group teacher-question panel-option">\
                        <div class="form-group panel-teacher">' + groupDom + 
                        '</div>\
                        <div class="form-group J_checkList margin-left3">'
                            + limitDom +
                        '</div>\
                    </div>',
            delDom = '<a href="javascript:;" class="margin-top J_delTeacher">删除组别</a>';
		$('.teacher-question:eq(-1)').after(dom);
		$('.teacherName').last().html('<span class="requires">*</span>考核组别'+optionLength);
        $('.panel-teacher:eq(-1)').append(delDom);
		$('.J_delTeacher:eq(-2)').css('display','none');
	}
	/*
		删除考核项
	*/
	function delOption(){
		var option = $('.J_delOption:eq(-1)').parents('.panel-option'),
			optionType = $('.J_delOption:eq(-1)').parents('.panel-option').next();
		option.remove();//本条考核项移除
		optionType.remove();//答题形式移除
        $('.J_checkList').each(function(){
            $(this).find('.J_checkOption:eq(-1)').remove();//考核项的每个组别数量上限移除
        })
		$('.J_delOption:eq(-1)').css('display','');//上一条的删除按钮显示
	}

	/*
		删除考核对象
	*/
	function delTeacher(){
        $('.teacher-question:eq(-1)').remove();
		$('.J_delTeacher:eq(-1)').css('display','');//上一条的删除按钮显示
	}
    /*
		保存问卷时验证问题外面的内容是否正确
	*/
	function formValidatorAddForm(){
		$('.J_formKaohe').bootstrapValidator({
            message: 'This value is not valid',
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                title: {
                    validators: {
                        notEmpty: {
                            message: '标题不能为空'
                        }
                    }
                },
                owner: {
                    validators: {
                        notEmpty: {
                            message: '发布人不能为空'
                        }
                    }
                }
            }
        });
	}
	/*
		保存问卷时验证optionForm的内容是否正确
	*/
	function formValidatorAllQuestionForm(i,optionLength){
		$('.J_optionForm').eq(i).bootstrapValidator({
            message: 'This value is not valid',
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                questionTitle: {
                    validators: {
                        notEmpty: {
                            message: '问题名称不能为空'
                        }
                    }
                },
                requirement: {
                    validators: {
                        notEmpty: {
                            message: '问题要求不能为空'
                        }
                    }
                },
                option: {
                    validators: {
                        notEmpty: {
                            message: '选项不能为空'
                        }
                    }
                }
            }
        });
	}
    /*
        保存问卷时验证teacherForm的内容是否正确
    */
    function formValidatorAllTeacherQuestionForm(i,optionLength){
        $('.J_teacherForm').eq(i).bootstrapValidator({
            message: 'This value is not valid',
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                remindaheadDays: {
                    validators: {
                        notEmpty: {
                            message: '考核数量上限不能为空'
                        },
                        regexp: {
                            regexp: /^[1-9]\d*$/,
                            message: '请输入正整数'
                        }
                    }
                }
            }
        });
    }
	/*
		验证问卷截止时间是否正确
	*/
	function validEndTime(){
		var 
			endTime = $('.J_endTime').val();

		if(endTime == ''){
			if($('.endTimeName').length == 0){
				$('.J_endTime').after('<i class="form-control-feedback has-error glyphicon glyphicon-remove styleColor" data-bv-icon-for="owner" style=""></i>')
				$('.J_validStyle').after('<small class="endTimeName has-error help-block" data-bv-validator="notEmpty" data-bv-for="name" data-bv-result="INVALID" style="color:#a94442;">登记截止时间不能为空</small>');
				$('.J_fontStyle').css('color', '#a94442')
			}
			return false;	
		}else{
			if($('.endTimeName').length > 0){
				$('.endTimeName').remove();
				$('.styleColor').remove();
				$('.J_fontStyle').css('color', '#3c763d')
			}
			return true;
		}
	}
    /*
		保存
	*/
	function save(e){
		var 
			checkList = $(".J_formKaohe").serializeObject(),
            limitNum,
            groupList = [],
            optionList = [],//考核项+答题形式列表
            groupLen = $('.panel-teacher').length,//考核组别的长度
            optionLength = $('.J_optionList').length;//考核项的个数
        //获取考核组别的值
        for(i=0; i<groupLen; i++){
            var groupI = $('.panel-teacher').eq(i),//第i个考核组别
                subjectId, gradeId, roleList = [], limitList = [],
                courseGrade = $('.J_courseGrade').eq(i).val(),
                selectCourse = groupI.find('.J_selectCourse').val(),
                selectGrades = groupI.find('.J_selectGrade').val();
            if(courseGrade == 0){
                subjectId = "0";
                gradeId = "0";
            }else if(courseGrade == 1){
                subjectId = selectCourse;
                gradeId = "0";
            }else if(courseGrade == 2){
                subjectId = "0";
                gradeId = selectGrades;
            }
            
            //考核组别的数量上限
            for(j=0; j<optionLength; j++){
                var limitNum =  groupI.next().find('.J_limitNum').eq(j).val();
                    grLimitIndex = groupI.next().find('.J_limitNum').eq(j).attr('limitIndex');
                limitList[j] = {
                    limitNum: limitNum,
                    limitIndex: grLimitIndex
                }
            }
            groupList[i] = {
                role: "1",
                subjectId: subjectId,
                gradeId: gradeId,
                limitList: limitList 
            };
        }
        //获取考核项的值
        for(k=0; k<optionLength; k++){
            var optionK = $('.J_optionList').eq(k),//第k个选项
                opLimitIndex = optionK.find('.J_option').attr('limitIndex'),
                option = optionK.find('.J_option').val(),//第k个选项的值
                optionType = optionK.next().find('.optionsRadios:checked').val();//第k个问题类型

            optionList[k] = {
                content: option,
                type: optionType,
                limitIndex: opLimitIndex
            };
         }
        jQuery.extend(checkList, {
            groupList: groupList,
            optionList: optionList
         });
		$.ajax({
	        type: jQuery.url.CheckManagement.sendCheckForm.type,
	        url: jQuery.url.CheckManagement.sendCheckForm.url,
	        contentType: "application/json; charset=utf-8",
	        data: JSON.stringify(checkList),
            // data: checkList,
	        dataType: "json",
	        success: function (rs) {
	            if( rs.code == 0){
	            	LiterTip("提示信息", "发布成功！");
                    setTimeout(function(){
                        window.location.href= "/admin/assess/list";
                    }, 1000);
	            }else{ 
	                Alert("提示信息", "返回参数不正确");
	            }
	        },  
	        error: function (rs) {
	            Alert("提示信息", "请求失败！"); 
	        }
	    });
	}
	/*
		选择多选按钮，提示多选的要求
	*/
	function showRequirement(e){
		var checked = $(e.target).val(),
			optionType = $(e.target).parents('.optionType'),
            limitNum,
            indexKey = $(optionType).index('.optionType');//当前optionType在所有optionType中的索引
	   if(checked == 1){
            $('.J_checkList').each(function(){
                limitNum = $(this).find(".J_checkOption").eq(indexKey).find(".J_limitNum");
                limitNum.attr("disabled", "disabled");
            })
		}
		if(checked == 2){
            $('.J_checkList').each(function(){
                limitNum = $(this).find(".J_checkOption").eq(indexKey).find(".J_limitNum");
                limitNum.removeAttr("disabled");
            })
		}
	}

	/*
		点击收起，收起当前问题框
	*/
	function retractQuestion(e){
		var box = $(e.target).parents('.box'),//面板
			top = $(e.target).parents('.top'),//问题栏
			main = top.siblings('.panel-question'),//问题主体
			retract = $(e.target),//收起按钮
			edit = $(e.target).siblings('.J_edit'),//编辑按钮
			del = $(e.target).siblings('.J_del'),//删除按钮
			retractForm = retract.parents('.top').siblings('.panel-question').children('.J_optionForm'),//需要验证的表单
			optionLength = retractForm.children('.panel-option').length;//当前要收起的问题中，选项的个数，用于验证

		if(retractForm.data('bootstrapValidator')){//如果已经验证过了，就清除验证，然后再验证
			retractForm.data('bootstrapValidator').destroy();
		}

		formValidatorRetractQuestionForm(optionLength);

		var 
			data = retractForm.data('bootstrapValidator');
        if (data) {
            data.validate();

            if (!data.isValid()) {
                return false;
            }else{
            	main.hide();
				box.css('paddingBottom','0');//下边有个白色的条，是因为之前改了样式，有padding
				retract.css('display','none');
				edit.removeClass('hidden');
				del.css('display','block');	
                return true;
            }
        }	
	}
	/*
		点击编辑，展开当前问题框
	*/
	function editQuestion(e){
		var box = $(e.target).parents('.box'),//面板
			top = $(e.target).parents('.top'),//问题栏
			main = top.siblings('.panel-question'),//问题主体
			retract = $(e.target).siblings('.J_retract'),//收起按钮
			edit = $(e.target),//编辑按钮
			del = $(e.target).siblings('.J_del');//删除按钮

		main.show();
		box.css('paddingBottom','15px');//下边有个白色的条，是因为之前改了样式，有padding
		retract.css('display','block');
		edit.addClass('hidden');
		del.css('display','block');	
	}
	/*
		点击删除，删除当前问题框
	*/
	function delQuestion(e){
		var box = $(e.target).parents('.box'),
			length = $('.J_optionForm').length;//问题有多少个

		if(length<2){//删除之前就只有一个问题
			$('.J_del').css('color','grey');
			return false;
		}else{
			box.remove();
			valQuestionTitle();
			if(length<3){//这个是删除之后只有一个问题
				$('.J_del').css('color','grey');
			}
		}
	}
	/*
		点击删除，删除当前问题框之后，重新检查问题框的标题
		（主要是防止在中间删除问题）
	*/
	function valQuestionTitle(){
		var box = $('.box'),
			length = box.length,
			i;
		for(i=0;i<length;i++){
			$('.top-left').eq(i).html('问题'+(i+1));
		}
	}
	/**
     * 更换角色隐藏年级和科目实现
     */
	function selectRoleChange(e){
		var 
			roleSelected = $(e.target).val(),
            course = $(e.target).parents('.J_group').next('.J_course'),
            grade = $(e.target).parents('.J_group').next().next();

		$(e.target).find("option:selected").each(function(i){ 
			if(roleSelected == 0){ 
				course.addClass('hidden');
				grade.addClass('hidden');
			}else if(roleSelected == 1){
				course.removeClass('hidden');
				grade.addClass('hidden');
			}else if(roleSelected == 2){
				course.addClass('hidden');
				grade.removeClass('hidden');
			}
		});
	}
});